package com.yuanjing.xiangqinxiangai.plugin.auth

import android.text.TextUtils
import com.baidu.idl.face.platform.LivenessTypeEnum
import org.json.JSONException
import org.json.JSONObject

/**
 * 与控制台交互的配置信息
 * Created by v_liujialu01 on 2020/8/10.
 */
class ConsoleConfig {
    var illumination: Float = 40f // 最小光照阈值
        private set
    var blur: Float = 0.5f // 模糊阈值
        private set
    var useOcr: Boolean = false // 是否使用Ocr
        private set
    var maxIllumination: Float = 220f // 最大光照阈值
        private set
    var leftEyeOcclu: Float = 0.8f // 左眼遮挡阈值
        private set
    var rightEyeOcclu: Float = 0.8f // 右眼遮挡阈值
        private set
    var noseOcclu: Float = 0.8f // 鼻子遮挡阈值
        private set
    var mouthOcclu: Float = 0.8f // 嘴巴遮挡阈值
        private set
    var leftCheekOcclu: Float = 0.8f // 左脸颊遮挡阈值
        private set
    var rightCheekOcclu: Float = 0.8f // 右脸颊遮挡阈值
        private set
    var chinOcclu: Float = 0.8f // 下巴遮挡阈值
        private set
    var pitch: Int = 20 // 抬头低头阈值
        private set
    var yaw: Int = 18 // 向左向右转头阈值
        private set
    var roll: Int = 20 // 偏头阈值
        private set

    var isFaceVerifyRandom: Boolean = false
        private set
    private val actions: MutableList<LivenessTypeEnum?> = ArrayList()

    /**
     * 场景信息：String类型，方案Id
     */
    var planId: String = "" // 是活体类型
        private set

    /**
     * 活体类型：0:炫彩+动作、1:动作活体、2:静默活体、3：静默活体+炫彩
     */
    var faceLiveType: Int = 0 // 是活体类型
        private set
    var faceActionNum: Int = 0 // 是活体类型
        private set
    var riskScore: Double = 80.0 // 公安验证是否是同一人的阈值设定
        private set
    var liveScore: Float = 0.8f // 活体分数
        private set

    // 用于从控制台获取，作为入参传入公安验证接口
    var onlineImageQuality: String? = null
        private set
    var onlineLivenessQuality: String? = null
        private set

    fun getActions(): List<LivenessTypeEnum?> {
        return actions
    }

    /**
     * 解析json文件的内容
     *
     * @param jsonObject JSON数据
     * @throws JSONException JSON异常
     */
    @Throws(Exception::class)
    fun parseFromJSONObject(jsonObject: JSONObject) {
        // 获取version 字段
        val version = jsonObject.optString("version")
        if (TextUtils.isEmpty(version)) {
            return
        }

        if ("3.0.0" == version) {
            parseFromJSON(jsonObject)
        } else {
            throw JSONException("初始配置读取失败, 版本号获取不正确")
        }
    }

    @Throws(Exception::class)
    private fun parseFromJSON(jsonObject: JSONObject) {
        val jsonImageQuality = jsonObject.optJSONObject("localImageQuality")
        var jsonQualityLevel: JSONObject? = null
        val jsonLoose = jsonImageQuality!!.optJSONObject("loose")
        val jsonNormal = jsonImageQuality.optJSONObject("normal")
        val jsonStrict = jsonImageQuality.optJSONObject("strict")
        jsonQualityLevel = if (jsonLoose != null && jsonLoose.length() > 0) {
            jsonLoose
        } else if (jsonNormal != null && jsonNormal.length() > 0) {
            jsonNormal
        } else if (jsonStrict != null && jsonStrict.length() > 0) {
            jsonStrict
        } else {
            throw JSONException("初始配置读取失败, localImageQuality json为空")
        }

        if (jsonQualityLevel != null) {
            illumination = jsonQualityLevel.optDouble("minIllum").toFloat()
            maxIllumination = jsonQualityLevel.optDouble("maxIllum").toFloat()
            blur = jsonQualityLevel.optDouble("blur").toFloat()
            leftEyeOcclu = jsonQualityLevel.optDouble("leftEyeOcclusion").toFloat()
            rightEyeOcclu = jsonQualityLevel.optDouble("rightEyeOcclusion").toFloat()
            noseOcclu = jsonQualityLevel.optDouble("noseOcclusion").toFloat()
            mouthOcclu = jsonQualityLevel.optDouble("mouseOcclusion").toFloat()
            leftCheekOcclu = jsonQualityLevel.optDouble("leftContourOcclusion").toFloat()
            rightCheekOcclu = jsonQualityLevel.optDouble("rightContourOcclusion").toFloat()
            chinOcclu = jsonQualityLevel.optDouble("chinOcclusion").toFloat()
            pitch = jsonQualityLevel.optInt("pitch")
            yaw = jsonQualityLevel.optInt("yaw")
            roll = jsonQualityLevel.optInt("roll")
        }

        // ocr
        val collection = jsonObject.optInt("collection")
        if (collection == 1) {
            useOcr = collection == 1
        }

        // 动作随机
        val randomFlag = jsonObject.optString("faceVerifyActionOrder")
        if (ACTION_RANDOM == randomFlag) {
            isFaceVerifyRandom = true
        }

        onlineImageQuality = jsonObject.optString("onlineImageQuality")
        onlineLivenessQuality = jsonObject.optString("onlineLivenessQuality")

        val ja = jsonObject.optJSONArray("faceVerifyAction")

        if (ja != null) {
            for (i in 0 until ja.length()) {
                val action = ja.getString(i)
                if (actionKVMap[action] == null) {
                    throw JSONException("初始配置读取失败, JSON格式不正确")
                }
                actions.add(actionKVMap[action])
            }
        }

        planId = jsonObject.optString("planId")
        faceLiveType = jsonObject.optInt("faceLivenessType")
        faceActionNum = jsonObject.optInt("faceActionNum")
        riskScore = jsonObject.optDouble("policeThreshold")
        liveScore = jsonObject.optDouble("livenessThreshold").toFloat()
    }

    companion object {
        /* 动作活体类型 */
        private val actionKVMap: MutableMap<String, LivenessTypeEnum?> = HashMap()

        init {
            actionKVMap["eye"] = LivenessTypeEnum.Eye
            actionKVMap["mouth"] = LivenessTypeEnum.Mouth
            actionKVMap["headRight"] = LivenessTypeEnum.HeadRight
            actionKVMap["headLeft"] = LivenessTypeEnum.HeadLeft
            actionKVMap["headUp"] = LivenessTypeEnum.HeadUp
            actionKVMap["headDown"] = LivenessTypeEnum.HeadDown
            actionKVMap["headShake"] = LivenessTypeEnum.HeadShake
            actionKVMap["headUpDown"] = LivenessTypeEnum.HeadUpDown
        }

        /* 随机*/
        private const val ACTION_RANDOM = "random"
    }
}
